package com.example.test.service;

import com.example.test.entity.Product;
import com.example.test.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
//
@Service
public class ProductService {

    //前端相对路径，与src同级，用于放上传后的图片
    private static final String UPLOAD_DIR = "uploads/";
    //实现图片覆盖，更新最新图片删除之前图片，改为upload绝对路径，结合自身地址，需修改
    private static final String ABSOLUTE_UPLOAD_DIR = "C:\\Users\\86183\\Desktop\\jiaoyi\\uploads";
    @Autowired
    private ProductMapper productMapper;

    public Product saveProduct(Product product, MultipartFile file, String username) throws IOException {
        if (file != null && !file.isEmpty()) {
            String fileName = System.currentTimeMillis() + "-" + encodeFileName(file.getOriginalFilename());
            Path localFilePath = Paths.get(ABSOLUTE_UPLOAD_DIR + fileName);
            Files.copy(file.getInputStream(), localFilePath);
            product.setImage(UPLOAD_DIR + fileName); // Save relative path in database
        }
        product.setSellerUsername(username); // 设置卖方用户名信息
        productMapper.insertProduct(product);
        return product;
    }

    public List<Product> getAllProducts() {
        return productMapper.getAllProducts();
    }

    public Product updateProduct(Long id, Product updatedProduct, MultipartFile file, String username) throws IOException {
        Product product = productMapper.getProductById(id);
        if (product != null) {
            product.setName(updatedProduct.getName());
            product.setDescription(updatedProduct.getDescription());
            product.setQuantity(updatedProduct.getQuantity());
            product.setPrice(updatedProduct.getPrice());
            product.setIfground(updatedProduct.getIfground());

            if (file != null && !file.isEmpty()) {
                // Delete old image using absolute path
                Files.deleteIfExists(Paths.get(ABSOLUTE_UPLOAD_DIR + getFileNameFromPath(product.getImage())));

                String fileName = System.currentTimeMillis() + "-" + encodeFileName(file.getOriginalFilename());
                Path localFilePath = Paths.get(ABSOLUTE_UPLOAD_DIR + fileName);
                Files.copy(file.getInputStream(), localFilePath);
                product.setImage(UPLOAD_DIR + fileName); // Save relative path in database
            }
            product.setSellerUsername(username); // 设置卖方用户名信息
            productMapper.updateProduct(product);
        }
        return product;
    }

    public void deleteProduct(Long id) {
        Product product = productMapper.getProductById(id);
        if (product != null) {
            try {
                // Delete image using absolute path
                Files.deleteIfExists(Paths.get(ABSOLUTE_UPLOAD_DIR + getFileNameFromPath(product.getImage())));
            } catch (IOException e) {
                e.printStackTrace();
            }
            productMapper.deleteProduct(id);
        }
    }

    private String encodeFileName(String fileName) {
        return fileName.replaceAll("[^a-zA-Z0-9\\.\\-]", "_");
    }

    private String getFileNameFromPath(String path) {
        return Paths.get(path).getFileName().toString();
    }

    public Product queryById(Long id) {
        Product product = productMapper.getProductById(id);
        return product;
    }
    public void updateQuantity(List<Product>products) {
        products.forEach(product -> {
            productMapper.updatequantity(product.getId(), product.getQuantity());
        });
    }
    public List<Product> checkProduct() {
        return productMapper.check();
    }
}
